package service

import (
	"context"
	"errors"
	"fmt"
	"patient-srv/basic/config"
	patient "patient-srv/basic/proto"
	"patient-srv/handler/model"
	"time"

	"gorm.io/gorm"
)

// GetDoctorSchedule 获取医师排班 - 从 doctor-srv 获取排班信息（这里暂时返回模拟数据）
func (s *PatientServiceServer) GetDoctorSchedule(ctx context.Context, req *patient.GetDoctorScheduleRequest) (*patient.DoctorScheduleResponse, error) {
	// TODO: 调用 doctor-srv 获取排班信息
	// 这里返回模拟数据，实际应该调用医生服务

	return &patient.DoctorScheduleResponse{
		Message: "获取成功",
		Schedules: []*patient.ScheduleInfo{
			{
				Id:              1,
				DoctorId:        req.DoctorId,
				ScheduleDate:    req.Date,
				StartTime:       "09:00",
				EndTime:         "12:00",
				MaxAppointments: 20,
				BookedCount:     5,
				ClinicAddress:   "门诊楼3楼",
				ClinicRoom:      "301",
				Period:          1, // 上午
				Fee:             50.00,
			},
		},
	}, nil
}

// CreateAppointment 创建预约
func (s *PatientServiceServer) CreateAppointment(ctx context.Context, req *patient.CreateAppointmentRequest) (*patient.CreateAppointmentResponse, error) {
	// 1. 验证就诊人信息
	var patientInfo model.Patient
	err := config.GlobalDB.Where("id = ? AND user_id = ?", req.PatientId, req.UserId).First(&patientInfo).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return &patient.CreateAppointmentResponse{Message: "就诊人信息不存在"}, nil
		}
		return nil, err
	}

	// 2. TODO: 调用 doctor-srv 验证医生和排班信息，获取挂号费
	fee := 50.0 // 暂时写死，实际应该从排班信息中获取

	// 3. 创建预约记录
	appointment := &model.Appointment{
		UserID:          req.UserId,
		DoctorID:        req.DoctorId,
		ScheduleID:      req.ScheduleId,
		PatientID:       req.PatientId,
		VisitType:       int(req.VisitType),
		AppointmentDate: req.AppointmentDate,
		TimeSlot:        req.TimeSlot,
		Status:          1, // 待支付
		Fee:             fee,
		Remark:          req.Remark,
		CreatedAt:       time.Now(),
		UpdatedAt:       time.Now(),
	}

	if err := config.GlobalDB.Create(appointment).Error; err != nil {
		return nil, err
	}

	// 4. 创建订单
	orderNo := model.GenerateOrderNo(1) // 1表示预约挂号订单
	order := &model.Order{
		OrderNo:   orderNo,
		UserID:    req.UserId,
		OrderType: 1, // 预约挂号
		Status:    1, // 待支付
		Amount:    fee,
		RelatedID: appointment.ID,
		CreatedAt: time.Now(),
		UpdatedAt: time.Now(),
	}

	if err := config.GlobalDB.Create(order).Error; err != nil {
		return nil, err
	}

	// 5. 更新预约记录的订单ID
	config.GlobalDB.Model(appointment).Update("order_id", order.ID)

	return &patient.CreateAppointmentResponse{
		Message:       "预约创建成功",
		AppointmentId: appointment.ID,
		OrderId:       order.ID,
		OrderNo:       order.OrderNo,
	}, nil
}

// GetAppointmentDetail 获取预约详情
func (s *PatientServiceServer) GetAppointmentDetail(ctx context.Context, req *patient.GetAppointmentDetailRequest) (*patient.AppointmentDetailResponse, error) {
	var appointment model.Appointment
	err := config.GlobalDB.Where("id = ? AND user_id = ?", req.AppointmentId, req.UserId).First(&appointment).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return &patient.AppointmentDetailResponse{Message: "预约记录不存在"}, nil
		}
		return nil, err
	}

	// 获取就诊人信息
	var patientInfo model.Patient
	config.GlobalDB.Where("id = ?", appointment.PatientID).First(&patientInfo)

	// TODO: 调用 doctor-srv 获取医生信息
	doctorName := fmt.Sprintf("医生%d", appointment.DoctorID)

	return &patient.AppointmentDetailResponse{
		Message: "获取成功",
		Appointment: &patient.AppointmentInfo{
			Id:              appointment.ID,
			UserId:          appointment.UserID,
			DoctorId:        appointment.DoctorID,
			DoctorName:      doctorName,
			PatientId:       appointment.PatientID,
			PatientName:     patientInfo.Name,
			VisitType:       int32(appointment.VisitType),
			AppointmentDate: appointment.AppointmentDate,
			TimeSlot:        appointment.TimeSlot,
			Status:          int32(appointment.Status),
			Fee:             appointment.Fee,
			ClinicAddress:   appointment.ClinicAddress,
			Remark:          appointment.Remark,
			CreatedAt:       appointment.CreatedAt.Format("2006-01-02 15:04:05"),
		},
	}, nil
}

// GetAppointmentList 获取预约列表
func (s *PatientServiceServer) GetAppointmentList(ctx context.Context, req *patient.GetAppointmentListRequest) (*patient.AppointmentListResponse, error) {
	var appointments []model.Appointment
	query := config.GlobalDB.Where("user_id = ?", req.UserId)

	// 如果指定状态，添加条件
	if req.Status > 0 {
		query = query.Where("status = ?", req.Status)
	}

	// 分页
	page := req.Page
	pageSize := req.PageSize
	if page < 1 {
		page = 1
	}
	if pageSize < 1 {
		pageSize = 10
	}
	offset := (page - 1) * pageSize

	// 查询总数
	var total int64
	query.Model(&model.Appointment{}).Count(&total)

	// 查询列表
	err := query.Order("id DESC").Offset(int(offset)).Limit(int(pageSize)).Find(&appointments).Error
	if err != nil {
		return nil, err
	}

	var result []*patient.AppointmentInfo
	for _, appt := range appointments {
		// 获取就诊人信息
		var patientInfo model.Patient
		config.GlobalDB.Where("id = ?", appt.PatientID).First(&patientInfo)

		result = append(result, &patient.AppointmentInfo{
			Id:              appt.ID,
			UserId:          appt.UserID,
			DoctorId:        appt.DoctorID,
			DoctorName:      fmt.Sprintf("医生%d", appt.DoctorID),
			PatientId:       appt.PatientID,
			PatientName:     patientInfo.Name,
			VisitType:       int32(appt.VisitType),
			AppointmentDate: appt.AppointmentDate,
			TimeSlot:        appt.TimeSlot,
			Status:          int32(appt.Status),
			Fee:             appt.Fee,
			ClinicAddress:   appt.ClinicAddress,
			Remark:          appt.Remark,
			CreatedAt:       appt.CreatedAt.Format("2006-01-02 15:04:05"),
		})
	}

	return &patient.AppointmentListResponse{
		Message:      "获取成功",
		Appointments: result,
		Total:        int32(total),
	}, nil
}

// CancelAppointment 取消预约
func (s *PatientServiceServer) CancelAppointment(ctx context.Context, req *patient.CancelAppointmentRequest) (*patient.BaseResponse, error) {
	// 查询预约记录
	var appointment model.Appointment
	err := config.GlobalDB.Where("id = ? AND user_id = ?", req.AppointmentId, req.UserId).First(&appointment).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return &patient.BaseResponse{Message: "预约记录不存在"}, nil
		}
		return nil, err
	}

	// 检查预约状态，只有待支付和待就诊状态可以取消
	if appointment.Status != 1 && appointment.Status != 2 {
		return &patient.BaseResponse{Message: "当前状态不允许取消"}, nil
	}

	// 更新预约状态为已取消
	if err := config.GlobalDB.Model(&appointment).Updates(map[string]interface{}{
		"status":     4, // 已取消
		"remark":     req.Reason,
		"updated_at": time.Now(),
	}).Error; err != nil {
		return nil, err
	}

	// 如果有关联订单，也更新订单状态
	if appointment.OrderID > 0 {
		config.GlobalDB.Model(&model.Order{}).Where("id = ?", appointment.OrderID).Updates(map[string]interface{}{
			"status":     3, // 已取消
			"updated_at": time.Now(),
		})
	}

	// TODO: 调用 doctor-srv 释放排班名额

	return &patient.BaseResponse{Message: "取消成功"}, nil
}
